﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text.pdf;

namespace P3.Modules.SharePoint.PDF2Lib.Layouts.P3.Modules.SharePoint.PDF2Lib
{
    public partial class PDF2LibConfig : LayoutsPageBase
    {

        public static readonly string Temp_PropertyKey = "Temp_CurrentUser_PropertyKey";

        private SPWeb currentWeb = SPContext.Current.Web;

        private string TempPropertyValue
        {
            get
            {
                if (currentWeb.Properties.ContainsKey(Temp_PropertyKey))
                {
                    return currentWeb.Properties[Temp_PropertyKey];
                }
                else return "";
            }
            set
            {

                if (currentWeb.Properties.ContainsKey(Temp_PropertyKey))
                {
                    currentWeb.Properties[Temp_PropertyKey] = value;
                }
                else
                {
                    currentWeb.Properties.Add(Temp_PropertyKey, value);
                }
                currentWeb.Properties.Update();
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            ClearErrorSummary();

            if (!IsPostBack)
            {
                Guid guid = new Guid(Page.Request.QueryString["ListId"]);
                SPWeb currentWeb = SPContext.Current.Web;
                SPList library = SPContext.Current.Web.Lists.GetList(guid, true);
                string settingsValue;
                Pdf2LibSaveProperties.Pdf2LibSaveProperties.loadSettings(currentWeb, guid, out settingsValue);

                SPQuery Query = new SPQuery();
                Query.Query = @"<Where><Eq>
                     <FieldRef Name='DocIcon' />
                    <Value Type='Computed'>pdf</Value>
                    </Eq>
                    </Where>";

                SPListItemCollection PdfFilesList = library.GetItems(Query);

                SPFieldCollection LibFields = library.Fields;


                PopulateDropdownList(PdfFilesList);

                PopulateLibraryColumsList(LibFields);

                if (PdfFilesList.Count > 0)
                {
                    PopulatePdfFieldsList(PdfFilesList[0], library);
                }
                UpdateListBoxes(settingsValue);

            }
            base.OnLoad(e);
        }

        private void PopulateLibraryColumsList(SPFieldCollection LibFields)
        {
            foreach (SPField field in LibFields)
            {
                if (!string.IsNullOrEmpty(field.Title))
                {
                    if ((!field.ReadOnlyField) || (!field.Hidden) || (!field.Sealed))
                    {
                        LibColsListbox.Items.Add(new ListItem(field.Title));
                    }
                }
            }
        }

        protected void PdfFilesListDropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListItem selectedItem = PdfFilesListDropDown.SelectedItem;

            Guid guid = new Guid(Page.Request.QueryString["ListId"]);
            SPWeb currentWeb = SPContext.Current.Web;
            SPList library = SPContext.Current.Web.Lists.GetList(guid, true);

            SPListItem item = library.GetItemById(Convert.ToInt32(selectedItem.Value));
            PopulatePdfFieldsList(item, library);
            RemoveDuplicatePdfFieldsItem(currentWeb, guid);

            ClearErrorSummary();
        }

        private void RemoveDuplicatePdfFieldsItem(SPWeb currentWeb, Guid LibraryGuid)
        {
            string settingsValue = TempPropertyValue; //

            if (settingsValue.IndexOf(';') == 0) { settingsValue = settingsValue.Remove(0, 1); }

            if (settingsValue != ";" && !string.IsNullOrEmpty(settingsValue))
            {
                string[] pdfFields_LibCol_Pairs = settingsValue.Split(new char[] { ';' });

                for (int k = 0; k < pdfFields_LibCol_Pairs.Length; k++)
                {
                    string[] keyValPair = pdfFields_LibCol_Pairs[k].Split(new string[] { " : " }, StringSplitOptions.RemoveEmptyEntries);

                    if (keyValPair.Count() == 2)
                    {
                        if (!string.IsNullOrEmpty(keyValPair[0]))
                        {
                            try
                            {
                                PdfFieldsListbox.Items.FindByText(keyValPair[0]).Enabled = false;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
            }
        }


        private void PopulatePdfFieldsList(SPListItem item, SPList Library)
        {
            IDictionary<string, AcroFields.Item> pdfFields = GetPdfFileFields(item, Library);

            if (pdfFields != null)
            {
                PdfFieldsListbox.Items.Clear();

                foreach (string str in pdfFields.Keys)
                {
                    PdfFieldsListbox.Items.Add(new ListItem(str));
                }
            }
        }

        private void PopulateDropdownList(SPListItemCollection PdfFilesList)
        {
            foreach (SPListItem item in PdfFilesList)
            {
                PdfFilesListDropDown.Items.Add(new ListItem(item.File.Name, item.ID.ToString()));
            }
        }

        private IDictionary<string, AcroFields.Item> GetPdfFileFields(SPListItem item, SPList library)
        {
            if (item != null)
            {
                if (item.File.Name.ToLower().EndsWith(".pdf"))
                {
                    SPFile spFile = item.File;

                    PdfReader pdfreader = new PdfReader(spFile.OpenBinary());

                    IDictionary<string, AcroFields.Item> pdfFields = pdfreader.AcroFields.Fields;

                    return pdfFields;
                }
            }

            return null;
        }

        private void UpdateListBoxes(string settingsValue)
        {
            if (settingsValue.IndexOf(';') == 0) { settingsValue = settingsValue.Remove(0, 1); }

            if (settingsValue != ";" && !string.IsNullOrEmpty(settingsValue))
            {
                string[] pdfFields_LibCol_Pairs = settingsValue.Split(new char[] { ';' });

                for (int k = 0; k < pdfFields_LibCol_Pairs.Length; k++)
                {
                    string[] keyValPair = pdfFields_LibCol_Pairs[k].Split(new string[] { " : " }, StringSplitOptions.RemoveEmptyEntries);

                    if (!string.IsNullOrEmpty(pdfFields_LibCol_Pairs[k]))
                    {
                        MappedListBox.Items.Add(new ListItem(pdfFields_LibCol_Pairs[k]));
                    }
                    if (keyValPair.Count() == 2)
                    {
                        if (!string.IsNullOrEmpty(keyValPair[0]) && !string.IsNullOrEmpty(keyValPair[1]))
                        {
                            try
                            {
                                LibColsListbox.Items.FindByText(keyValPair[1]).Enabled = false;
                                PdfFieldsListbox.Items.FindByText(keyValPair[0]).Enabled = false;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
            }

        }

        public void insertLibrarySettings(Guid library, SPWeb web)
        {
            string libraryString = library.ToString();

            string settings = TempPropertyValue;
            if (!web.Properties.ContainsKey(libraryString))
            {
                web.Properties.Add(library.ToString(), settings);
            }
            else
            {
                web.Properties[library.ToString()] = settings;
            }
            web.Properties.Update();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            closeDialog();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Guid guid = new Guid(Page.Request.QueryString["ListId"]);
            SPWeb currentWeb = SPContext.Current.Web;
            insertLibrarySettings(guid, currentWeb);
            closeDialog();
            //Response.Redirect(currentWeb.Lists.GetList(guid, false).DefaultView.ServerRelativeUrl);
        }

        private void closeDialog()
        {
            string isDlg = Page.Request.QueryString["IsDlg"];
            if (!String.IsNullOrEmpty(isDlg) && isDlg == "1")
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "SP.UI.ModalDialog.commonModalDialogClose();", true);
            }
        }


        protected void Map_click(object sender, EventArgs e)
        {
            ClearErrorSummary();

            Guid LibraryGuid = new Guid(Page.Request.QueryString["ListId"]);
            SPWeb currentWeb = SPContext.Current.Web;

            if ((PdfFieldsListbox.GetSelectedIndices().Count() == 1) && (LibColsListbox.GetSelectedIndices().Count() == 1))
            {
                if (currentWeb.Properties.ContainsKey(LibraryGuid.ToString()))
                {
                    MapSelectedItem(currentWeb, LibraryGuid);
                }
                else
                {
                    currentWeb.Properties.Add(LibraryGuid.ToString(), string.Empty);
                    MapSelectedItem(currentWeb, LibraryGuid);
                }
            }
        }

        private void MapSelectedItem(SPWeb currentWeb, Guid LibraryGuid)
        {
            string SettingsString = TempPropertyValue;

            string CurSelectedString = PdfFieldsListbox.SelectedItem.Text + " : " + LibColsListbox.SelectedItem.Text;

            if (!SettingsString.Contains(CurSelectedString))
            {
                SettingsString += CurSelectedString + ";";
                TempPropertyValue = SettingsString;

                MappedListBox.Items.Add(new ListItem(PdfFieldsListbox.SelectedItem.Text + " : " + LibColsListbox.SelectedItem.Text));

                PdfFieldsListbox.SelectedItem.Enabled = false;
                LibColsListbox.SelectedItem.Enabled = false;

                PdfFieldsListbox.SelectedItem.Selected = false;
                LibColsListbox.SelectedItem.Selected = false;
            }
        }

        protected void UnMap_click(object sender, EventArgs e)
        {
            ClearErrorSummary();

            if (MappedListBox.SelectedItem != null)
            {
                Guid LibraryGuid = new Guid(Page.Request.QueryString["ListId"]);
                SPWeb currentWeb = SPContext.Current.Web;

                if (currentWeb.Properties.ContainsKey(LibraryGuid.ToString()))
                {
                    UnMapSelectedItem(currentWeb, LibraryGuid);
                }
            }
            else
            {
                ShowErrorSummary("Please select an item to UnMap");
            }
        }

        private void UnMapSelectedItem(SPWeb currentWeb, Guid LibraryGuid)
        {
            string[] SplitStr = new string[] { " : " };
            string[] UnmapArr = MappedListBox.SelectedItem.Text.Split(SplitStr, StringSplitOptions.RemoveEmptyEntries);

            string SettingsString = TempPropertyValue;

            string CurSelectedString = MappedListBox.SelectedItem.Text;

            if (SettingsString.Contains(CurSelectedString) && !string.IsNullOrEmpty(CurSelectedString))
            {
                if ((PdfFieldsListbox.Items.Count > 0) && (LibColsListbox.Items.Count > 0))
                {

                    if (PdfFieldsListbox.Items.FindByText(UnmapArr[0]) != null && LibColsListbox.Items.FindByText(UnmapArr[1]) != null)
                    {
                        PdfFieldsListbox.Items.FindByText(UnmapArr[0]).Enabled = true;
                        LibColsListbox.Items.FindByText(UnmapArr[1]).Enabled = true;

                        MappedListBox.Items.Remove(MappedListBox.SelectedItem);

                        SettingsString = SettingsString.Remove(SettingsString.IndexOf(CurSelectedString), CurSelectedString.Length + 1);
                        TempPropertyValue = SettingsString;
                    }
                    else
                    {
                        if (PdfFieldsListbox.Items.FindByText(UnmapArr[0]) == null)
                        {
                            ShowErrorSummary("Cannot find " + UnmapArr[0] + " in the selected PDF file");
                        }
                        else if(LibColsListbox.Items.FindByText(UnmapArr[1]) == null)
                        {
                            ShowErrorSummary("Cannot find " + UnmapArr[1] + " in the Library Columns");
                        }
                    }
                }
            }
        }


        private void ClearErrorSummary()
        {
            this.ErrorSummary.Visible = false;
            this.ErrorSummary.Text = "";
        }

        private void ShowErrorSummary(string msg)
        {
            this.ErrorSummary.Visible = true;
            this.ErrorSummary.Text = msg;
        }

    }
}
